package jnpf.database.source.impl;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.handler.TableNameHandler;
import jnpf.database.data.DataSourceContextHolder;
import jnpf.database.enums.datatype.DataTypeEnum;
import jnpf.database.enums.datatype.DtDmEnum;
import jnpf.database.model.DataTypeModel;
import jnpf.database.model.DbTableFieldModel;
import jnpf.database.model.DbTableModel;
import jnpf.database.model.dto.DbConnDTO;
import jnpf.database.source.DbBase;
import jnpf.database.sql.SqlBase;
import jnpf.database.sql.impl.SqlDM;
import jnpf.database.util.CommonUtil;
import jnpf.database.util.DataSourceUtil;
import jnpf.database.util.JdbcUtil;
import jnpf.exception.DataException;
import jnpf.util.StringUtil;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.List;

/**
 * 达梦模型
 *
 * @author JNPF开发平台组 YY
 * @version V3.2.0
 * @copyright 引迈信息技术有限公司
 * @date 2021/10/06
 */
@Slf4j
public class DbDM extends DbBase {

    public static final String DB_ENCODE = "DM8";
    public static final String CONN_URL = "jdbc:dm://{host}:{port}/{dbname}";

    @Override
    public void setDbType() {
        mpDbType = DbType.DM;
        connUrlEncode = "dm";
        dbEncode = DB_ENCODE;
        driver = "dm.jdbc.driver.DmDriver";
    }

    @Override
    public SqlBase getSqlBase() {
        return new SqlDM(this);
    }

    @Override
    public DataTypeModel getDataTypeModel(DataTypeEnum dte) {
        return dte.getDtDmEnum().getDataTypeModel();
    }

    @Override
    public DataTypeModel getDataTypeModel(String dbFieldType) {
        for (DtDmEnum dtDmEnum : DtDmEnum.values()) {
            if (dbFieldType.equals(dtDmEnum.getDbFieldType())) {
                return dtDmEnum.getDataTypeModel();
            }
        }
        return null;
    }

    @Override
    public String getConnUrl(String prepareUrl, String host, Integer port, String dbName) {
        if (StringUtil.isEmpty(prepareUrl)) {
            prepareUrl = CONN_URL;
        }
        return super.getConnUrl(prepareUrl, host, port, dbName);
    }

    @Override
    public void setDynamicMap(HashMap<String, TableNameHandler> map, DbTableModel dbTableModel) {
        map.put(dbTableModel.getTable(), (sql, tableName) -> DataSourceContextHolder.getDatasourceName() + "." + dbTableModel.getTable());
    }

    @Override
    public DbTableFieldModel getFieldModel(ResultSet result) {
        return new DbTableFieldModel();
    }


    @Override
    public String getDbTime(Connection conn) {
        StringBuilder sql = new StringBuilder();
        sql.append("select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') as TIME ");
        return dbTimeCommon(conn, sql);
    }

    @Override
    public String getReplaceSql(String sql, String table, DataSourceUtil dbSourceOrDbLink) {
        /**
         * 说明：一个实例对应一个数据库，多个模式，一个用户对应一个模式，同oracle
         * 表空间需默认：MAIN
         */
        return CommonUtil.getReplaceSql(sql, table, dbSourceOrDbLink,
                false,
                true,
                true);
    }


    public static void setDmTableModel(DbConnDTO connDTO, List<DbTableModel> tableModelList) {
        //达梦特殊方法
        try {
            @Cleanup Connection dmConn = connDTO.getConn();
            tableModelList.forEach(tm -> {
                try {
                    Integer sum = DbDM.getSum(dmConn, tm.getTable());
                    tm.setSum(sum);
                } catch (DataException e) {
                    e.printStackTrace();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Integer getSum(Connection connection, String table) throws DataException {
        String sql = "SELECT COUNT(*) as F_SUM FROM " + table;
        return JdbcUtil.queryOneInt(connection, sql, "F_SUM");
    }

}
